package cn.sumpu.app.guoguojie.biz.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import cn.sumpu.app.guoguojie.biz.DoingBiz;
import cn.sumpu.app.guoguojie.biz.FamilyBiz;
import cn.sumpu.app.guoguojie.biz.IdentifierBiz;
import cn.sumpu.app.guoguojie.biz.PictorialBiz;
import cn.sumpu.app.guoguojie.biz.PictorialTopicBiz;
import cn.sumpu.app.guoguojie.constant.DoingType;
import cn.sumpu.app.guoguojie.constant.OwnerType;
import cn.sumpu.app.guoguojie.dao.DoingDao;
import cn.sumpu.app.guoguojie.dao.PictorialDao;
import cn.sumpu.app.guoguojie.domain.Doing;
import cn.sumpu.app.guoguojie.domain.DoingPictorial;
import cn.sumpu.app.guoguojie.domain.DoingPictorialVisit;
import cn.sumpu.app.guoguojie.domain.DoingPicture;
import cn.sumpu.app.guoguojie.domain.DoingProduct;
import cn.sumpu.app.guoguojie.domain.Family;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.Experience;
import cn.sumpu.app.guoguojie.util.PageModel;

public class PictorialBizImpl implements PictorialBiz {

    @Autowired
    private DoingBiz          doingBiz;
    @Resource
    private FamilyBiz         familyBiz;
    @Resource
    private PictorialTopicBiz pictorialTopicBiz;
    @Resource
    private IdentifierBiz     identifierBiz;

    private PictorialDao      pictorialDao;
    private DoingDao          doingDao;

    public void setPictorialDao(PictorialDao pictorialDao) {
        this.pictorialDao = pictorialDao;
    }

    public void setDoingDao(DoingDao doingDao) {
        this.doingDao = doingDao;
    }

    @Override
    @Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
    public DoingPictorial savePictorial(DoingPictorial dp) throws AppBusinessException {
        if (dp == null)
            return null;
        String picId = dp.getIdentifier();

        Doing doing = new Doing();
        doing.setIdentifier(picId);
        doing.setMember(dp.getMember());
        doing.setOwner(dp.getFamily());
        doing.setOwnerType(OwnerType.FAMILY.getValue());
        doing.setContent(dp.getTitle());
        doing.setType(DoingType.PICROOT.getValue());
        doing.setPostIp(dp.getPostIp());

        if (Common.empty(picId)) {
            picId = identifierBiz.generateId("doing");
            dp.setIdentifier(picId);
            pictorialDao.insertPictorial(dp);
            // 创建画报的同时创建一条微博
            doing.setIdentifier(picId);
            doingDao.insert(doing);

            //插入画报主题 
            if (Common.notEmptyStr(dp.getPictorialTopic())) {
                String[] str = dp.getPictorialTopic().split(",");
                for (String topicId : str) {
                    pictorialTopicBiz.addDoingPictorialTopic(picId, topicId, new Date(), new Date());
                }
            }
        } else {
            dp.setGmtModified(new Date());
            pictorialDao.updatePictorial(dp);
            doingDao.update(doing);

            //更新画报主题
            pictorialTopicBiz.updatePictorialTopic(dp);
        }

        return dp;
    }

    @Override
    public DoingPictorial updatePictorial(DoingPictorial dp) throws AppBusinessException {
        if (dp == null)
            return null;
        pictorialDao.updatePictorial(dp);
        return dp;
    }

    @Override
    public PageModel getPictorialList(String family, Integer page) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("family", family);

        Integer startId = (page - 1) * Common.PAGE_SIZE_PICTORIAL;
        map.put("startId", startId);
        map.put("pageSize", Common.PAGE_SIZE_PICTORIAL);
        List<DoingPictorial> picList = pictorialDao.getPictorialList(map);
        int count = pictorialDao.getPictorialListCount(map);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(picList);
        pm.setPageSize(Common.PAGE_SIZE_PICTORIAL);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + Common.PAGE_SIZE_PICTORIAL - 1) / Common.PAGE_SIZE_PICTORIAL);
        return pm;
    }

    // 通过画报的ID得到画报

    @Override
    public DoingPictorial getPictorialById(String identifier) throws AppBusinessException {
        if (Common.empty(identifier))
            return null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("identifier", identifier);
        List<DoingPictorial> picList = pictorialDao.getPictorialList(map);
        if (picList != null && picList.size() > 0) {
            return picList.get(0);
        }
        return null;
    }

    @Override
    public PageModel getPictorialList6(String family, Integer page) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("family", family);

        Integer startId = (page - 1) * Common.PAGE_SIZE_PICTORIAL_6;
        map.put("startId", startId);
        map.put("pageSize", Common.PAGE_SIZE_PICTORIAL_6);
        List<DoingPictorial> picList = pictorialDao.getPictorialList(map);
        int count = pictorialDao.getPictorialListCount(map);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(picList);
        pm.setPageSize(Common.PAGE_SIZE_PICTORIAL_6);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + Common.PAGE_SIZE_PICTORIAL_6 - 1) / Common.PAGE_SIZE_PICTORIAL_6);
        return pm;
    }

    @Override
    public PageModel getMorePictorialList2(String family, String pictorial) throws AppBusinessException {
        int page = 1;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("family", family);
        map.put("notPictorial", pictorial);

        Integer startId = (page - 1) * Common.PAGE_SIZE_PICTORIAL_2;
        map.put("startId", startId);
        map.put("pageSize", Common.PAGE_SIZE_PICTORIAL_2);
        List<DoingPictorial> picList = pictorialDao.getPictorialList(map);
        int count = pictorialDao.getPictorialListCount(map);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(picList);
        pm.setPageSize(Common.PAGE_SIZE_PICTORIAL_2);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + Common.PAGE_SIZE_PICTORIAL_2 - 1) / Common.PAGE_SIZE_PICTORIAL_2);
        return pm;
    }

    @Override
    public String joinPictorial(Member member, Doing doing, String pictorial, String picproId, int picType) throws AppBusinessException {
        if (Common.empty(picproId))
            return null;
        if (picType != 1 && picType != 2)
            return null;
        if (doing == null)
            return null;
        int epicpro = getExistPicpro(picType, picproId, pictorial);
        if (epicpro > 0)
            return "exist";
        String doingId = identifierBiz.generateId("doing");
        doing.setIdentifier(doingId);
        doing.setMember(member.getIdentifier());
        doing.setOwner(member.getFamily());
        doing.setOwnerType(OwnerType.FAMILY.getValue());
        doing.setType(DoingType.PICTORIAL.getValue());
        doing.setPictorial(pictorial);
        // 发布画报

        if (picType == 1) {
            DoingPicture doingPicture = doingBiz.getPictureById(picproId);
            if (doingPicture != null) {
                doing.setToMember(doingPicture.getMember());
                doingPicture.setDoing(doingId);
                doingPicture.setMember(member.getIdentifier());
                doingPicture.setFamily(member.getFamily());
                doingPicture.setIdentifier(identifierBiz.generateId("doing_picture"));
                // 画报内的图片
                doingDao.insertDoingPicture(doingPicture);

            }
        } else if (picType == 2) {
            DoingProduct doingProduct = doingBiz.getProductById(picproId);
            if (doingProduct != null) {
                doing.setToMember(doingProduct.getMember());

                doingProduct.setDoing(doingId);
                doingProduct.setMember(member.getIdentifier());
                doingProduct.setFamily(member.getFamily());
                doingProduct.setIdentifier(identifierBiz.generateId("doing_product"));
                // 画报内的商品
                doingDao.insertDoingProduct(doingProduct);
            }
        }

        //如果画报里面第一次收藏6个内容 则新手奖励 
        if (Experience.isOnce(member.getFamilyObj().getRookieReward(), 5)) {
            DoingPictorial dp = getPictorialById(pictorial);
            if ((dp.getPicAmount() + dp.getProAmount()) == 5) {
                String rookieReward = Experience.replaceRookieReward(member.getFamilyObj().getRookieReward(), 5);
                Family f = new Family();
                f.setDoorplate(member.getFamily());
                f.setRookieReward(rookieReward);
                familyBiz.updateFamily(f);
                member.getFamilyObj().setRookieReward(rookieReward);
            }
        }

        //更新画报的图片的数量
        DoingPictorial p = new DoingPictorial();
        p.setIdentifier(pictorial);
        //如果是图片
        if (picType == 1) {
            p.setPicAmount(1);
        } else if (picType == 2) {
            //如果是商品
            p.setProAmount(1);
        }
        p.setGmtModified(new Date());
        pictorialDao.updatePictorial(p);
        doingDao.insert(doing);
        return "success";
    }

    @Override
    public int getExistPicpro(Integer picType, String picproId, String pictorial) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("picType", picType);
        map.put("picproId", picproId);
        map.put("pictorial", pictorial);
        return pictorialDao.getExistPicpro(map);
    }

    @Override
    public PageModel getPicDoingList(String family, String pictorial, Integer page) throws AppBusinessException {
        if (Common.empty(page)) {
            page = 1;
        }
        int pageSize = Common.PAGE_SIZE_POSTDOING_MYFAMILY;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("family", family);
        map.put("pictorial", pictorial);
        int count = doingDao.getDoingByMyFamilyCount(map);

        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<Doing> doingList = doingDao.getDoingByMyFamily(map);

        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(doingList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }

    @Override
    @Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
    public void deletePictorial(String family, String pictorial) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("family", family);
        map.put("identifier", pictorial);
        map.put("pictorial", pictorial);
        // 删除画报下所有的微博
        pictorialDao.deleteDoingByPic(map);
        // 删除画报下微博所包含的图片
        pictorialDao.deletePictureByPic(map);
        // 删除画报下微博所包含的产品
        pictorialDao.deleteProductByPic(map);
        // 删除画报
        pictorialDao.deletePictorial(map);
        // 删除微博
        doingBiz.deleteDoing(family, pictorial);
    }

    @Override
    public int getPicorialCount(String family) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("family", family);
        return pictorialDao.getPictorialListCount(map);
    }

    // 查询访问画报的人
    @Override
    public List<DoingPictorialVisit> selectPictorialVisitList(String picorialId) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pictorialId", picorialId);
        return pictorialDao.selectPictorialVisitList(map);
    }

    // 访问画报插入访问记录同时更新访问量
    public void insterPictorialVisit(DoingPictorialVisit doingPictorialVisit) throws AppBusinessException {

        // 是否已访问
        DoingPictorialVisit visitor = pictorialDao.selectVisitor(doingPictorialVisit);
        if (visitor != null) {
            // 是
            doingPictorialVisit.setGmtModified(new Date());
            pictorialDao.updatePictorialVisit(doingPictorialVisit);
        } else {
            // 否
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("pictorialId", doingPictorialVisit.getPictorialId());
            List<DoingPictorialVisit> selectVisitList = pictorialDao.selectPictorialVisitList(map);

            if (selectVisitList.size() >= 8) {
                // 满8人
                pictorialDao.updateNewVisit(doingPictorialVisit);
            } else {
                // 未到8
                pictorialDao.insertPictorialVisit(doingPictorialVisit);
            }

        }
    }

    public void updatePicView(String pictorialId) throws AppBusinessException {
        // 画报访问量加+1
        DoingPictorial pictorial = new DoingPictorial();
        pictorial.setIdentifier(pictorialId);
        pictorial.setViewAmount(1);
        pictorialDao.updatePictorial(pictorial);
    }

    // 查询推荐的画报
    @Override
    public List<DoingPictorial> getPictorialByChannel(String channel, Integer number) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("channel", channel);
        map.put("startId", 0);
        map.put("pageSize", number);
        return pictorialDao.getPictorialByChannel(map);
    }

    //查询每个分类推荐的第一个
    @Override
    public List<DoingPictorial> getHotPictorialNo1(String channel, String status) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("channel", channel);
        map.put("status", Common.emptyStr(status) ? "('1')" : status);
        return pictorialDao.getHotPictorialNo1(map);
    }

    /**
     * author BruceZhang
     * @param channel 频道ID
     * @param status 状态
     * @param type 分类
     * @param page 页码
     * @return	查询最热的画报
     * @throws AppBusinessException
     */
    @Override
    public PageModel getHotPictorialByCategory(String channel, String status, String type, Integer page, String topic) throws AppBusinessException {
        page = Common.empty(page) ? 1 : page;
        Integer pageSize = 32;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("channel", channel);
        map.put("type", type);
        map.put("topic", topic);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<DoingPictorial> pList = pictorialDao.getPictorialByChannel(map);
        int count = getPictorialCountByChannel(channel, status, type, topic);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(pList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }

    //查询推荐的画报的总记录数
    @Override
    public Integer getPictorialCountByChannel(String channel, String status, String type, String topic) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("channel", channel);
        map.put("status", Common.emptyStr(status) ? "('1')" : status);
        map.put("type", type);
        map.put("topic", topic);
        return pictorialDao.getPictorialCountByChannel(map);
    }

    //查询最新的画报
    @Override
    public PageModel getPictorialNew(String type, Integer page, String topic) throws AppBusinessException {
        page = Common.empty(page) ? 1 : page;

        return getPictorialNew(type, page, topic, 10, null);
    }

    @Override
    public PageModel getTopicDetail(Integer page, Integer times, String topic) throws AppBusinessException {
        int allTimes = 10; // 一页分多少次取 
        int pageSize = 120; // 一页显示多少条
        if (page == null || page <= 0) {
            page = 1;
        }
        if (times == null || times <= 0) {
            times = 1;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("topic", topic);
        map.put("startId", (page - 1) * pageSize + (times - 1) * (pageSize / allTimes));
        map.put("pageSize", pageSize / allTimes);
        List<DoingPictorial> pList = pictorialDao.getPictorialNew(map);
        int count = getPictorialCountNew(null, topic);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(pList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }

    //查询最新的画报
    @Override
    public PageModel getPictorialNew(String type, Integer page, String topic, int pageSize, Map<String, Object> con) throws AppBusinessException {
        page = Common.empty(page) ? 1 : page;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", type);
        map.put("topic", topic);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        if (!Common.empty(con)) {
            map.putAll(con);
        }
        List<DoingPictorial> pList = pictorialDao.getPictorialNew(map); 
        int count = getPictorialCountNew(type, topic);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(pList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }

    //查询最新的画报的总记录数
    @Override
    public Integer getPictorialCountNew(String type, String topic) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", type);
        map.put("topic", topic);
        return pictorialDao.getPictorialCountNew(map);
    }

    //画报主页的分页
    @Override
    public PageModel getHotPictorialIndex(String channel, String status, Integer page) throws AppBusinessException {
        page = Common.empty(page) ? 1 : page;
        Integer pageSize = 20;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("channel", channel);
        map.put("status", Common.emptyStr(status) ? "('1')" : status);
        //		map.put("startId", (page - 1) * pageSize + 6);
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<DoingPictorial> pList = pictorialDao.getPictorialByChannel(map);
        int count = getPictorialCountByChannel(channel, status, null, null) - 6;
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(pList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }

    @Override
    public PageModel getPictorialNewIndex(Integer page) throws AppBusinessException {
        page = Common.empty(page) ? 1 : page;
        Integer pageSize = 20;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startId", (page - 1) * pageSize);
        map.put("pageSize", pageSize);
        List<DoingPictorial> pList = pictorialDao.getPictorialNew(map);
        int count = getPictorialCountNew(null, null);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(pList);
        pm.setPageSize(pageSize);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + pageSize - 1) / pageSize);
        return pm;
    }

    //查询前N条画报记录
    @Override
    public List<DoingPictorial> getPictorialBruce(int size) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("size", size);
        return pictorialDao.getPictorialBruce(map);
    }
}
